package org.framework.superutil.j2se;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import net.sf.json.JSONObject;

/**
 * 网络工具包
 * @author <a href="http://www.xdemo.org/">http://www.xdemo.org/</a>
 * 252878950@qq.com
 */
public class NetUtils {
	
	public final static Logger LOGGER = Logger.getLogger(NetUtils.class);

	/**
	 * IP地址是否可达
	 * @param ip
	 * @return boolean
	 */
	public static boolean isReachable(String ip) {
		InetAddress address;
		try {
			address = InetAddress.getByName(ip);
			if (address.isReachable(5000)) {
				return true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	/**
	 * 判断网址是否有效<br>
	 * <b>注意</b> 对于404页面，如果被电信或者联通劫持了，也会返回200的状态，这个是不准确的
	 * @param url URL对象
	 * @return boolean
	 */
	public static boolean isReachable(URL url){
		
		boolean reachable=false;
		HttpURLConnection httpconn=null;
		HttpsURLConnection httpsconn=null;
		int code=0;
		
		try {
			if(url.getProtocol().equals("https")){
				httpsconn=(HttpsURLConnection)url.openConnection();
				code=httpsconn.getResponseCode();
			}else{
				httpconn=(HttpURLConnection)url.openConnection();
				code=httpconn.getResponseCode();
			}
			System.out.println(code);
			if(code==200){
				reachable=true;
			}
		} catch (Exception e) {
			reachable=false;
		}
		
		return reachable;
	}
	
	/**
	 * 实现Ping命令
	 * @param ip
	 * @return Ping的字符串换行使用java的换行符"\n"，如果ping不同返回null
	 */
	public static String ping(String ip) {
		String res = "";
		String line = null;
		try {
			Process pro = Runtime.getRuntime().exec("ping " + ip);
			BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream(), "GBK"));
			while ((line = buf.readLine()) != null) {
				if (!line.equals("")) {
					res+=String.valueOf(line)+"\n";
				}
			}
		} catch (Exception e) {
			res = null;
		}
		return res;
	}
	
	// 获取MAC地址的方法
	private static String getMACAddress(InetAddress ia) throws Exception {
		// 获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
		byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		// 下面代码是把mac地址拼装成String
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < mac.length; i++) {
			if (i != 0) {
				sb.append("-");
			}
			// mac[i] & 0xFF 是为了把byte转化为正整数
			String s = Integer.toHexString(mac[i] & 0xFF);
			sb.append(s.length() == 1 ? 0 + s : s);
		}
		// 把字符串所有小写字母改为大写成为正规的mac地址并返回
		return sb.toString().toUpperCase();
	}
	
   /** 
	* 描述：获取IP地址
	* @author huaping hu 
	* @date 2016年6月1日下午5:25:44
	* @param request
	* @return
	*/
	public static String getIpAddress(HttpServletRequest request){
	
		String ip = request.getHeader("x-forwarded-for");
		
		if(ip == null || ip.length() ==0 || "nuknown".equalsIgnoreCase(ip)){
		
		ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() ==0 || "nuknown".equalsIgnoreCase(ip)){
		
		ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() ==0 || "nuknown".equalsIgnoreCase(ip)){
		
		ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	
	/**
	* 
	* 描述：获取IP+[IP所属地址]
	* @author huaping hu 
	* @date 2016年6月1日下午6:01:09
	* @param request
	* @return
	*/
	public static String getIpBelongAddress(HttpServletRequest request){
	
		String ip = getIpAddress(request);
		String belongIp = getIPbelongAddress(ip);
		
		return ip + belongIp;
	}
	/**
	* 
	* 描述：获取IP所属地址
	* @author huaping hu 
	* @date 2016年6月1日下午5:59:43
	* @param ip
	* @return
	*/
	public static String getIPbelongAddress(String ip){
	
		String ipAddress = "[]";
		try{
			//淘宝提供的服务地址
			String context = call("http://ip.taobao.com/service/getIpInfo.php?ip="+ip);
			JSONObject fromObject = JSONObject.fromObject(context);
			String code = fromObject.getString("code");
			if(code.equals("0")){
				JSONObject jsonObject = fromObject.getJSONObject("data");
				ipAddress =  "["+jsonObject.get("country")+"/" +jsonObject.get("city")+"]";
		    }
	    }catch(Exception e){
	    	LOGGER.error("获取IP所属地址出错",e);
	        e.printStackTrace();
	    }
	    return ipAddress;
	}
	/**
	* 
	* 描述：获取Ip所属地址
	* @author huaping hu 
	* @date 2016年6月1日下午5:38:55
	* @param urlStr
	* @return
	*/
	public static String call( String urlStr ){
	
		try {
		
		URL url = new URL(urlStr);
		HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
		
		httpCon.setConnectTimeout(3000);
		httpCon.setDoInput(true);
		httpCon.setRequestMethod("GET");
		
		int code = httpCon.getResponseCode();
		
		if(code == 200){
		return streamConvertToSting(httpCon.getInputStream());
		}
		} catch (Exception e) {
		LOGGER.error("获取IP所属地址出错",e);
		e.printStackTrace();
		}
		return null;
	}
	
	/**
	* 
	* 描述：将InputStream转换成String
	* @author huaping hu 
	* @date 2016年6月1日下午5:51:53
	* @param is
	* @return
	*/
	public static String streamConvertToSting(InputStream is){
	
		String tempStr = "";
		try {
		
		if(is == null) return null;
		ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
		byte[] by = new byte[1024];
		int len = 0;
		while((len = is.read(by))!=-1){
		arrayOut.write(by,0,len);
		}
		tempStr = new String(arrayOut.toByteArray());
		
		} catch (IOException e) {
			e.printStackTrace();
		}
		return tempStr;
	}
	
	public static void main(String[] args) {
	
		String context = call("http://ip.taobao.com/service/getIpInfo.php?ip=120.192.182.1");
		
		JSONObject fromObject = JSONObject.fromObject(context);
		JSONObject jsonObject = fromObject.getJSONObject("data");
		System.out.println(fromObject);
		System.err.println(jsonObject.get("city"));
	}

}
